﻿using MediatR;
using W.Purchase.API.Application.Command.ClientCommand;
using W.Purchase.Domain;
using W.Purchase.Domain.DTO;
using W.Purchase.Repository.Interface;
using W.Warehouse.Domain.DTO;
using static W.Purchase.Domain.DTO.ClientFanDTO;

namespace W.Purchase.API.Application.CommandHandler.ClientCommandHandler
{
    public class ClienContactFanCommandHandler : IRequestHandler<ClienContactFanCommand, ApiResult<ClientFanDTO>>
    {
        private readonly IClientContactRepository clientContact;
        private readonly IClientRepository clientRepository;
        private readonly IContactRepository contactRepository;
        public ClienContactFanCommandHandler(IClientContactRepository clientContact, IContactRepository contactRepository, IClientRepository clientRepository)
        {
            this.clientContact = clientContact;
            this.contactRepository = contactRepository;
            this.clientRepository = clientRepository;
        }

        public async Task<ApiResult<ClientFanDTO>> Handle(ClienContactFanCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ClientFanDTO> result = new ApiResult<ClientFanDTO>();
            try
            {
                
                var contac = await contactRepository.GetAllAsaync();
                var client = from a in await clientRepository.GetAllAsaync()
                             where a.IsDelete == false && a.ClientId == request.ClientId
                             select new ClientFanDTO
                             {
                                 ClientId = a.ClientId,
                                 ClientNo = a.ClientNo,
                                 ClientName = a.ClientName,
                                 ClientFax = a.ClientFax,
                                 ClientPhone = a.ClientPhone,
                                 ClientEmail = a.ClientEmail,
                                 ClientRemark = a.ClientRemark,
                                 clistCons = contac.Where(x => x.ContactId == a.ClientId).Select(x => new ClistConData
                                 {
                                     ContactId = x.ContactId,
                                     ContactName = x.ContactName,
                                     ContactAddress = x.ContactAddress,
                                     ContactPhone = x.ContactPhone,

                                 }).ToList()
                             };
                result.Data = client.FirstOrDefault();
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
    }
}
